<template>
  <div class="map-wrapper">
    <div class="mouse-tool-box">
      <a-card size="small">
        <!-- <div style="display: flex; gap: 10px; flex-direction: column; align-items: center"> -->
        <a-row :gutter="[10, 10]" style="width: 330px" justify="start">
          <a-col :span="24">
            <CustomRangePicker v-model:value="queryForm.create_time" @search="getStoreOrderList" />
          </a-col>
          <a-col :span="12">
            <a-input v-model:value.trim="queryForm.no" placeholder="单据编号" allow-clear @change="getStoreOrderList" />
          </a-col>
          <a-col :span="12">
            <Select style="width: 100%" name="Dealer" v-model:value="queryForm.dealer_id" placeholder="请选择经销商" @change="getStoreOrderList" />
          </a-col>
          <a-col :span="12">
            <Select style="width: 100%" name="Salesman" v-model:value="queryForm.salesman_id" placeholder="请选择业务员" @change="getStoreOrderList" />
          </a-col>
          <a-col :span="12">
            <Select style="width: 100%" name="Store" v-model:value="queryForm.store_id" placeholder="请选择门店" @change="getStoreOrderList" />
          </a-col>
          <a-col :span="12">
            <Select style="width: 100%" name="Warehouse" v-model:value="queryForm.warehouse_id" :fetch-params="selectFetchParams.warehouse" placeholder="请选择仓库" @change="getStoreOrderList" />
          </a-col>
          <a-col :span="12">
            <EnumSelect enum-name="ORDER_STATRS_ENUM" v-model:value="queryForm.order_type" placeholder="单据类型" @change="getStoreOrderList" />
          </a-col>
        </a-row>
        <!--  -->
        <!-- </div> -->
      </a-card>
      <a-card size="small">
        <a-button-group>
          <a-button @click="handleDrawEvent('')" :type="currentDrawEvent === '' ? 'primary' : 'default'">
            <div class="mouse-tool-btn">
              <Icon icon="svg-icon:tuodong"></Icon>
              <span>拖动</span>
            </div>
          </a-button>
          <a-button @click="handleDrawEvent('rectangle')" :type="currentDrawEvent === 'rectangle' ? 'primary' : 'default'">
            <div class="mouse-tool-btn">
              <Icon icon="svg-icon:juxing"></Icon>
              <span>矩形</span>
            </div>
          </a-button>
          <a-button @click="handleDrawEvent('polygon')" :type="currentDrawEvent === 'polygon' ? 'primary' : 'default'">
            <div class="mouse-tool-btn">
              <Icon icon="svg-icon:duobianxing"></Icon>
              <span>多边形</span>
            </div>
          </a-button>
          <a-button @click="handleDrawEvent('circle')" :type="currentDrawEvent === 'circle' ? 'primary' : 'default'">
            <div class="mouse-tool-btn">
              <Icon icon="svg-icon:yuan"></Icon>
              <span>圆形</span>
            </div>
          </a-button>
        </a-button-group>
      </a-card>
      <a-card v-show="currentDrawEvent !== ''" size="small">
        <a-radio-group v-model:value="drawType">
          <a-radio-button value="add">加单</a-radio-button>
          <a-radio-button value="subtract">减单</a-radio-button>
        </a-radio-group>
      </a-card>
    </div>

    <div id="container" :style="{ height: `${mapHeight}px` }"></div>
    <a-card class="order-box" size="small" :tabList="tabList" :activeTabKey="currentTabKey" @tabChange="onTabChange">
      <template #customTab="item">
        <a-badge :count="item.key === 'Selected' ? checkedOrderIds.length : storeOrderList.length - checkedOrderIds.length" :offset="[10, 10]">
          <span class="ant-card-head-title" :style="compactModeClass">
            {{ item.label }}
          </span>
        </a-badge>
      </template>
      <template #tabBarExtraContent>
        <DownCircleOutlined :rotate="orderCollapse ? 180 : 0" @click="orderCollapse = !orderCollapse" />
      </template>
      <template v-if="!orderCollapse">
        <a-list item-layout="horizontal" :data-source="orderList" :style="{ height: `${mapHeight - 150}px`, overflowY: 'auto' }" size="small">
          <template #renderItem="{ item, index }">
            <div @click="onSelectedOrder(item.id)" :class="{ 'store-order-item': true, active: checkedOrderIds.includes(item.id) }">
              <div class="no">{{ index + 1 }}</div>
              <div class="content">
                <div class="wait-time">
                  <a-tag :color="item.wait_time > 24 ? 'error' : 'warning'">
                    <template #icon>
                      <ClockCircleOutlined />
                    </template>
                    {{ item.wait_time }}小时
                  </a-tag>
                </div>
                <p class="line">
                  <span style="margin-right: 0.5em">{{ item?.name }}</span>
                  <span :style="{ color: item.type === 1 ? '#df5352' : '#8085a2' }">{{ item?.no }}</span>
                  <span style="float: right; cursor: pointer" @click.stop="moveMapCenter([item?.lon, item?.lat])"><AimOutlined /></span>
                </p>
                <p class="line">{{ item.address }}</p>
                <p class="line">
                  业务员：
                  <span>{{ item?.salesman_rename }}</span>
                </p>
                <p class="line">
                  单据日期：
                  <span>{{ item?.create_time }}</span>
                </p>
                <p class="line">
                  单据备注：
                  <span>{{ item?.remark }}</span>
                </p>
                <div class="order-info-line">
                  <span>{{ item.totalVolume }}m³</span>
                  <span>|</span>
                  <span>{{ item.totalWidth }} kg</span>
                  <span>|</span>
                  <span>￥{{ item.order_amount }}</span>
                </div>
              </div>
            </div>
          </template>
        </a-list>
        <a-card class="total-box" size="small">
          <p class="total-box-line">
            <span>
              体积&nbsp;&nbsp;&nbsp;&nbsp;订:
              <strong>{{ checkedOrderVolumeTotal.sales }}</strong>
              m³
            </span>
            <span>
              退:
              <strong>{{ checkedOrderVolumeTotal.refund }}</strong>
              m³
            </span>
          </p>
          <p class="total-box-line">
            <span>
              重量&nbsp;&nbsp;&nbsp;&nbsp;订:
              <strong>{{ checkedOrderWeightTotal.sales }}</strong>
              kg
            </span>
            <span>
              退:
              <strong>{{ checkedOrderWeightTotal.refund }}</strong>
              kg
            </span>
          </p>
          <p class="total-box-line">
            <span>
              金额&nbsp;&nbsp;&nbsp;&nbsp;订:
              <strong>{{ checkedOrderAmountTotal.sales }}</strong>
              元
            </span>
            <span>
              退: <strong>{{ checkedOrderAmountTotal.refund }}</strong>
              元
            </span>
          </p>
          <p class="total-box-line" style="flex-direction: column">
            <span>
              订:
              <strong>{{ checkedOrderCountTotal.sales }}</strong>
            </span>
            <span>
              退:
              <strong>{{ checkedOrderCountTotal.refund }}</strong>
            </span>
          </p>
        </a-card>
      </template>
      <template #actions>
        <div class="order-box-footer">
          <a-space>
            <a-checkbox v-model:checked="checkedAllOrder">全选</a-checkbox>
            <span v-show="currentTabKey === 'Selected'">已选中：{{ checkedOrderIds.length }}订单</span>
          </a-space>
          <a-button type="primary" @click="showSubmitModal(1)">保存</a-button>
          <!-- <a-button type="primary" @click="showSubmitModal(2)">装车</a-button> -->
        </div>
      </template>
    </a-card>
    <a-modal :visible="showSubmit" title="提交" @ok="submitTask(currentTaskType)" @cancel="showSubmit = false">
      <a-row :gutter="[10, 10]">
        <a-col :span="12">
          <Select name="Driver" style="width: 100%" v-model:value="currentDriverId" placeholder="配送司机" @change="onDriverChange" allowClear />
        </a-col>
        <a-col :span="12">
          <Select name="Driver" style="width: 100%" v-model:value="currentAssistDriverId" placeholder="协送员" @change="onEscortDriverChange" allowClear />
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import _ from 'lodash'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import Select from '@/components/business/select/index.vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { useUserStore } from '@/store/modules/user-store'
import { salesApi } from '@/api/business/sale/sales-api'
import { taskApi } from '@/api/business/logistics/delivery-api'
import { warehouseApi } from '@/api/business/storage/warehouse-api'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import location_fullfilled from '@/assets/images/logo/location_fullfilled.png'
import location_pending from '@/assets/images/logo/location_pending.png'
import location_active from '@/assets/images/logo/location_active.png'
import Icon from '@/components/framework/icon/index.vue'
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import { WAREHOUSE_TYPE, WAREHOUSE_ATTRIBUTE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
import EnumSelect from '@/components/framework/enum-select/index.vue'

const compactModeClass = inject('compactModeClass')
const route = useRoute()
const router = useRouter()
let map: any = null
let AMap: any = null
let mouseTool: any = null
const icons = {
  location_pending,
  location_active,
  location_fullfilled
}
const userStore = useUserStore()

// 地图高度
const mapHeight = ref(0)

// 初始化地图
function initMap() {
  checkedOrderIds.value = []
  window._AMapSecurityConfig = {
    securityJsCode: '98ed597fdab99b3580ded9e3d1f19d4e'
  }
  const loadMapConfig = {
    key: 'e3ad28f39ebf5c7d5fb1d7153fb2f3b4', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.LabelsLayer', 'AMap.MouseTool'] //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  }
  const mapConfig: any = {
    zoom: 14,
    zooms: [5, 20],
    center: userStore.getCenterLocal.map(Number),
    resizeEnable: true
  }

  AMapLoader.load(loadMapConfig).then(async (res) => {
    AMap = res
    // 渲染地图
    mapHeight.value = document.querySelector('.map-wrapper')?.clientHeight || 0
    map = new AMap.Map('container', mapConfig)
    // 创建鼠标工具
    mouseTool = new AMap.MouseTool(map)
    // 请求订单列表
    await getStoreOrderList()
    // 监听事件
    mouseTool.on('draw', function (event: any) {
      const path = event.obj.getPath()
      storesMarkers.value.forEach((item) => {
        const extData = item.getExtData()
        if (AMap.GeometryUtil.isPointInRing(item.getPosition(), path)) {
          if (drawType.value === 'add') {
            onMapSelectedOrder(extData.id)
          } else if (drawType.value === 'subtract') {
            onRemoveCheckedOrder(extData.id)
          }
        }
      })
      mouseTool.close(true)
      handleDrawEvent(currentDrawEvent.value)
    })
  })
}

// 添加网点坐标
const storesMarkers = ref([])
function addMarker() {
  // 创建LabelsLayer图层
  const labelsLayer = new AMap.LabelsLayer({
    zooms: [2, 20], // 设置可见级别范围
    zIndex: 1000, // 设置zIndex
    collision: false // 设置标签是否允许碰撞
  })

  storesMarkers.value = storeOrderList.value
    .filter((item) => item.lon && item.lat)
    .map((item) => {
      return new AMap.LabelMarker({
        position: new AMap.LngLat(item.lon, item.lat),
        name: item.name,
        extData: item,
        zooms: [2, 20],
        rank: 1,
        icon: {
          type: 'image',
          image: icons[item.type === 1 ? 'location_pending' : 'location_fullfilled'],
          size: [24, 24],
          anchor: 'bottom-center'
        },
        text: {
          content: `${item.index + 1}`,
          offset: [0, 20],
          style: {
            fontSize: 10,
            fontWeight: 'normal',
            fillColor: item.type === 1 ? '#fff' : '#000'
          }
        }
      })
    })
  // 添加监听事件
  storesMarkers.value.forEach((item) => {
    let infoWindow = null
    item.on('click', (e) => {
      const extData = e.target.getExtData()
      for (const item of storeOrderList.value) {
        if (item.store_id !== extData.store_id) continue
        onSelectedOrder(item.id)
      }
    })
    item.on('mouseover', (e) => {
      infoWindow = initWindow(e)
      infoWindow.open(map, item.getPosition())
    })
    item.on('mouseout', () => {
      infoWindow.close()
    })
  })
  labelsLayer.add(storesMarkers.value)
  map.add(labelsLayer)
}

// 信息窗体
function initWindow(e) {
  const extData = e.target.getExtData()

  const orders = storeOrderList.value
    .filter((item) => item.store_id === extData.store_id)
    .map((item, index) => {
      return `
        ${index > 0 ? '<div style="border-bottom: 1px solid #ccc;margin: 4px 0;"></div>' : ''}
        <span>单据号：${item.no} - ${item.type === 1 ? '销' : '退'}</span>
        <p style="margin-block: 0;">
          <span>订单金额：${item.order_amount.toFixed(2)}</span>
          <span>体积：${item.totalVolume.toFixed(2)}</span>
          <span>重量：${item.totalWidth.toFixed(2)}</span>
        </p>
      `
    })
  const content = `
    <div style="display:flex;flex-direction:column;gap:2px;border: 1px solid #ccc; padding: 10px;background-color: #fff;font-size: 12px">
      <span style="font-weight: bold">门店名称:${extData.name} - 共${orders.length}单</span>
      <span>${extData.address}</span>
  `
  const infoWindow = new AMap.InfoWindow({
    content: content + orders.join('') + '</div>',
    anchor: 'bottom-center',
    isCustom: true,
    closeWhenClickMap: true,
    offset: [10, -30]
  })
  return infoWindow
}

// 重新设置地图中心点
function moveMapCenter(val: Array<number | string>) {
  map.setCenter(val.map(Number))
}

// 绘制事件
const currentDrawEvent = ref('')
const drawType = ref<'add' | 'subtract'>('add')
function handleDrawEvent(type: string) {
  currentDrawEvent.value = type
  if (type === '') return mouseTool.close(true)
  mouseTool[type]({
    fillOpacity: 0
  })
}
onActivated(initMap)
onUnmounted(() => {
  checkedOrderIds.value = []
  map.value?.destroy()
})
// 搜索区域
const queryForm = ref({
  create_time: DEFAULT_TIME_RANGE.value,
  type: 1,
  is_delivery: 1,
  is_self: 1,
  status: '2,6',
  dealer_id: undefined,
  salesman_id: undefined,
  store_id: undefined,
  warehouse_id: undefined,
  order_type: undefined,
  no: ''
})
const queryFormOp = {
  type: QUERY_FORM_OP.全等查询,
  is_delivery: QUERY_FORM_OP.不等查询,
  is_self: QUERY_FORM_OP.不等查询,
  status: QUERY_FORM_OP.IN查询,
  create_time: QUERY_FORM_OP.范围查询,
  dealer_id: QUERY_FORM_OP.全等查询,
  salesman_id: QUERY_FORM_OP.全等查询,
  store_id: QUERY_FORM_OP.全等查询,
  warehouse_id: QUERY_FORM_OP.全等查询,
  order_type: QUERY_FORM_OP.全等查询,
  no: QUERY_FORM_OP['模糊查询']
}
// 获取司机/协送员列表
const showSubmit = ref(false)
let currentTaskType = 1
// 司机
const isWarehouse = ref(false)
async function onDriverChange(value) {
  if (value === currentAssistDriverId.value) currentAssistDriverId.value = undefined
  const res = await warehouseApi.checkDriver({ driver_id: value })
  isWarehouse.value = res.data.isWarehouse
  if (!res.data.isWarehouse) {
    message.error('该司机没有创建移动仓，请先创建移动仓')
  }
}
// Select查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询']
    },
    fields: 'id,name'
  }
}
// 协送员
function onEscortDriverChange(value) {
  if (value === currentDriverId.value) currentDriverId.value = undefined
}
// 查询参数
// const driverFetchParams = computed(() => ({ filter: { id: currentDriverId.value || currentAssistDriverId.value }, op: { id: QUERY_FORM_OP['不等查询'] } }))

function showSubmitModal(type: 1 | 2) {
  if (checkedOrderIds.value.length === 0) {
    return message.error('请选择订单')
  }
  currentTaskType = type
  showSubmit.value = true
}

// 右侧订单区域
// 订单列表折叠状态
const orderCollapse = ref(false)

// 订单列表
const storeOrderList = ref([])
let checkOrderSource = [] // 记录编辑时已分配的订单ID
async function getStoreOrderList() {
  checkedOrderIds.value = []
  storeOrderList.value = []
  currentTabKey.value = 'Unchecked'
  function handleOrderData(item, index) {
    return {
      order_id: item.id,
      id: item.id,
      index,
      name: item?.store?.store_name,
      store_id: item?.store?.id,
      lon: item?.store?.lon,
      lat: item?.store?.lat,
      address: item?.store?.address,
      order_amount: _(item.detail)
        .map(({ total_price }) => Number(total_price))
        .sum(),
      order_number: item.order_number,
      totalVolume: _(item.detail)
        .map(({ volume }) => Number(volume))
        .sum(),
      totalWidth: _(item.detail)
        .map(({ weight }) => Number(weight))
        .sum(),
      no: item.no,
      type: item.order_type,
      create_time: item.create_time,
      salesman_rename: item?.salesman?.rename,
      remark: item.remark,
      // 等待时间 = 当前时间 - 订单创建时间，转换为小时
      wait_time: dayjs().diff(dayjs(item.create_time), 'hour')
    }
  }
  try {
    const params = {
      filter: queryForm.value,
      op: queryFormOp,
      page: 1,
      limit: 99999
    }
    const res = await salesApi.queryList(params)
    const list = res.data.data
    if (route.query?.id && route.query?.driver_id) {
      currentDriverId.value = Number(route.query.driver_id)
      onDriverChange(currentDriverId.value)
      currentAssistDriverId.value = route.query.escort_driver_id === 'undefined' ? undefined : Number(route.query.escort_driver_id)
      const res = await taskApi.detailLoad({ id: route.query?.id })
      checkOrderSource = res.data.data.map(({ id }) => id)
      list.push(...res.data.data)
      checkedOrderIds.value = res.data.data.map(({ id }) => id)
    }
    storeOrderList.value = list.map(handleOrderData)
    addMarker()
  } catch (error) {
    if (error?.msg) {
      message.error(error.msg)
    }
  }
}

// 订单列表tab
const tabList = reactive([
  {
    label: '已选中',
    key: 'Selected'
  },
  {
    label: '待排单',
    key: 'Unchecked'
  }
])
const currentTabKey = ref('Unchecked')
function onTabChange(key: string) {
  currentTabKey.value = key
}
// 订单选择状态
const checkedOrderIds = ref<number[]>([])
// 订单全选
const checkedAllOrder = computed({
  get() {
    return checkedOrderIds.value.length === storeOrderList.value.length
  },
  set(val) {
    if (val) {
      checkedOrderIds.value = storeOrderList.value.map((item) => item.id)
      currentTabKey.value = 'Selected'
    } else {
      checkedOrderIds.value = []
      currentTabKey.value = 'Unchecked'
    }
  }
})

// 地图添加选中订单
function onMapSelectedOrder(id: number) {
  const checkedIds = new Set(checkedOrderIds.value)
  checkedIds.add(id)
  checkedOrderIds.value = Array.from(checkedIds)
}

// 右侧列表添加选中订单
function onSelectedOrder(id: number) {
  if (checkedOrderIds.value.includes(id)) {
    return onRemoveCheckedOrder(id)
  }
  checkedOrderIds.value.push(id)
  currentTabKey.value = 'Selected'
}

// 删除选中订单
function onRemoveCheckedOrder(id: number) {
  checkedOrderIds.value = checkedOrderIds.value.filter((item) => item !== id)
  currentTabKey.value = 'Unchecked'
}

// 根据已选择的单据选中状态过滤订单列表
const orderList = computed(() => {
  return storeOrderList.value.filter((item) => {
    if (currentTabKey.value === 'Selected') return checkedOrderIds.value.includes(item.id)
    return !checkedOrderIds.value.includes(item.id)
  })
})

// 已选择的销售订单合计信息
const checkedSalesOrderInfo = computed(() => {
  return _.filter(storeOrderList.value, (item) => checkedOrderIds.value.includes(item.id) && item.type === 1)
})
// 已选择的退货订单合计信息
const checkedRefundOrderInfo = computed(() => {
  return _.filter(storeOrderList.value, (item) => checkedOrderIds.value.includes(item.id) && item.type === 2)
})
// 体积
const checkedOrderVolumeTotal = computed(() => {
  return {
    sales: _.sumBy(checkedSalesOrderInfo.value, 'totalVolume').toFixed(2),
    refund: _.sumBy(checkedRefundOrderInfo.value, 'totalVolume').toFixed(2)
  }
})
// 重量
const checkedOrderWeightTotal = computed(() => {
  return {
    sales: _.sumBy(checkedSalesOrderInfo.value, 'totalWidth').toFixed(2),
    refund: _.sumBy(checkedRefundOrderInfo.value, 'totalWidth').toFixed(2)
  }
})
// 金额
const checkedOrderAmountTotal = computed(() => {
  return {
    sales: _.sumBy(checkedSalesOrderInfo.value, 'order_amount').toFixed(2),
    refund: _.sumBy(checkedRefundOrderInfo.value, 'order_amount').toFixed(2)
  }
})
// 数量
const checkedOrderCountTotal = computed(() => {
  const chartMap = new Map([
    ['整'.codePointAt(0), 0],
    ['中'.codePointAt(0), 0],
    ['散'.codePointAt(0), 0]
  ])

  function handleData(item: any) {
    return item.order_number
      ? item.order_number.split('-').map((item) => {
          return {
            numbers: item.match(/\d+/g).join(''),
            chinese: item.match(/[\u4e00-\u9fa5]+/g).join('')
          }
        })
      : []
  }

  function sumBy(params: any, source: Map<number | undefined, number>) {
    const sourceKey = params.chinese.codePointAt(0)
    const sourceNum = source.get(sourceKey)
    source.set(sourceKey, Number(sourceNum) + Number(params.numbers))
    return source
  }

  return {
    sales: _(checkedSalesOrderInfo.value)
      .map(handleData)
      .flatMapDeep()
      .reduce((prev, cur) => sumBy(cur, prev), _.cloneDeep(chartMap))
      .entries()
      .map(([chinese, number]) => [number, String.fromCharCode(chinese as number)])
      .toArray()
      .map((item) => item.join(''))
      .join(''),
    refund: _(checkedRefundOrderInfo.value)
      .map(handleData)
      .flatMapDeep()
      .reduce((prev, cur) => sumBy(cur, prev), _.cloneDeep(chartMap))
      .entries()
      .map(([chinese, number]) => [number, String.fromCharCode(chinese as number)])
      .toArray()
      .map((item) => item.join(''))
      .join('')
  }
})

// 监听订单变化
watch(
  () => checkedOrderIds.value,
  (newVal) => {
    // 设置图标
    for (const item of storesMarkers.value) {
      const extData = item.getExtData()
      if (newVal.includes(extData.id)) {
        item.setIcon({
          image: icons.location_active
        })
      } else {
        item.setIcon({
          image: extData.type === 1 ? icons.location_pending : icons.location_fullfilled
        })
      }
    }
  },
  {
    deep: true
  }
)

// 提交
// 当前司机
const currentDriverId = ref<number | undefined>(undefined)

// 当前协送员
const currentAssistDriverId = ref<number | undefined>(undefined)

async function submitTask(type) {
  if (!isWarehouse.value) {
    return message.error('该司机没有创建移动仓，请先创建移动仓')
  }
  if (currentDriverId.value === undefined) {
    return message.error('请选择司机')
  }
  const checkedOrders = storeOrderList.value.filter((item) => checkedOrderIds.value.includes(item.id))
  let order_ids: any = []
  if (route.query?.id) {
    const ids = new Set([checkOrderSource.map((id) => id), checkedOrders.map(({ order_id: id }) => id)].flat(1)) // 用于提交时的订单ID列表
    order_ids = Array.from(ids).map((id) => {
      return {
        id,
        is_delete: checkedOrders.findIndex((item) => item.order_id === id) === -1 ? 1 : 0 // 如果订单不在已分配列表中，则标记为删除
      }
    })
  } else {
    order_ids = checkedOrders.map(({ order_id: id }) => ({ id }))
  }
  const params = {
    order_ids: JSON.stringify(order_ids),
    driver_id: unref(currentDriverId) || '',
    escort_driver_id: unref(currentAssistDriverId) ?? '',
    status: type
  }

  try {
    if (route.query?.id) {
      params.id = route.query.id
    }
    const res = await taskApi[params?.id ? 'editLoad' : 'addLoad'](params)
    message.success(res.msg)
    getStoreOrderList()
    checkedOrderIds.value = []
    currentDriverId.value = undefined
    currentAssistDriverId.value = undefined
    showSubmit.value = false
    if (route.query?.id) {
      router.replace('/map')
    }
    router.back()
  } catch (error) {
    message.error(error.msg)
  }
}
</script>
<style lang="less" scoped>
.map-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  .mouse-tool-box {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 999;
    .mouse-tool-btn {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
  #container {
    width: 100%;
    height: auto;
  }
  .order-box {
    position: absolute;
    right: 0;
    top: 0;
    width: 450px;
    .store-order-item {
      position: relative;
      width: 98%;
      font-size: 12px;
      padding: 10px;
      margin-bottom: 5px;
      border-radius: 5px;
      background-color: #f8f9ff;
      cursor: pointer;
      border: 1px solid transparent;
      .wait-time :deep(.ant-tag > .anticon + span) {
        margin-inline-start: unset;
      }
      .no {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 14px;
      }
      .content {
        display: flex;
        flex-direction: column;
        padding-left: 30px;
        width: 100%;
        p {
          width: 100%;
          margin: 0;
          // white-space: nowrap;
          // overflow: hidden;
          // text-overflow: ellipsis;
        }
        .line {
          color: #8085a2;
        }
        .line span {
          color: #000;
        }
      }
      .order-info-line {
        display: flex;
        gap: 5px;
        align-items: center;
      }
    }
    .store-order-item.active,
    .store-order-item:hover {
      background-color: #eaf4f0;
      border: 1px solid @primary-color;
    }
  }
  .order-box-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 12px;
  }
  .total-box {
    position: absolute;
    left: -265px;
    bottom: 0px;
    width: 260px;
    font-size: 12px;
    .total-box-line {
      display: flex;
      justify-content: space-between;
      margin-bottom: 0;
      strong {
        font-size: 14px;
      }
      span {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
</style>
